using MicroMsg.Common.Algorithm;
using MicroMsg.Common.Event;
using MicroMsg.Common.Utils;
using MicroMsg.Resource.@string;
using MicroMsg.Scene;
using MicroMsg.Storage;
using MicroMsg.UI.Util;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Xml.Linq;
namespace MicroMsg.Manager
{
	public class MobileContactMgr
	{
		private const string dblLastSyncAddbookTimeStampKey = "dblLastSyncAddbookTimeStamp";
		private const string TAG = "MobileContactMgr";
		public const int STATUS_ERROR = 0;
		public const int STATUS_SYNCING = 1;
		public const int STATUS_SYNC_COMPLETE = 2;
		public const int TYPE_MOBILE = 0;
		public const int TYPE_EMAIL = 1;
		public const int STATUS_WEIXIN_OFF_IN_STG = 65536;
		public const int STATUS_WEIXIN_OFF = 0;
		public const int STATUS_WEIXIN_ON = 1;
		public const int STATUS_WEXIN_FRIEND = 2;
		public const int MM_CONTACTFLAG_NULL = 0;
		public const uint MM_CONTACTFLAG_CONTACT = 1u;
		public const uint MM_CONTACTFLAG_CHATCONTACT = 2u;
		public const uint MM_CONTACTFLAG_CHATROOMCONTACT = 4u;
		public const uint MM_CONTACTFLAG_BLACKLISTCONTACT = 8u;
		public const uint MM_CONTACTFLAG_DOMAINCONTACT = 16u;
		public const uint MM_CONTACTFLAG_HIDECONTACT = 32u;
		public const uint MM_CONTACTFLAG_ALL = 63u;
		private const string nDeviceContactCountKey = "nDeviceContactCount";
		private const string nLastUploadAndGetFriendResultKey = "nLastUploadAndGetFriendResult";
		private const int HEX_RADIX = 16;
		private const int LENGTH_OF_LONG = 8;
		private const double SYNC_ADDR_BOOK_LIMIT = 10800000.0;
		private const int UP_AND_GET_RESULT_SUCCESS = 1;
		private const int UP_AND_GET_RESULT_FAILED = -1;
		private EventWatcher mWatcherSyncComplete;
		private EventWatcher mWatcherUpAndGetResult;
		private int mStatus;
		private long mLastUpdateTime;
		private DelegateProgressBar mGetProgressBar;
		private List<PhoneNumInfo> mPhoneList;
		private List<PhoneNumInfo> mEmailList;
		private int contactNum;
		private EventWatcher mWatcherUpdateListResult;
		public bool syncContactFromDevice()
		{
			if (this.mStatus == 1)
			{
				return false;
			}
			this.mStatus = 1;
			this.startReadMobileAndEmail();
			return true;
		}
		public bool syncAndUploadContactFromDevice(DelegateProgressBar getProgressBar)
		{
			Log.smethod_5("MobileContactMgr", "start syncAndUploadContactFromDevice()");
			if (this.mStatus == 1)
			{
				return false;
			}
			this.mGetProgressBar = getProgressBar;
			if (this.mGetProgressBar == null)
			{
				return false;
			}
			this.mStatus = 1;
			if (this.mWatcherSyncComplete == null)
			{
				this.mWatcherSyncComplete = new EventWatcher(this, null, new EventHandlerDelegate(this.onEventHandlerSyncComplete));
				EventCenter.registerEventWatcher(EventConst.ON_SYNC_CONTACT_COMPLETE, this.mWatcherSyncComplete);
			}
			Log.smethod_5("MobileContactMgr", "start startReadMobileAndEmail()");
			this.startReadMobileAndEmail();
			return true;
		}
		private void onEventHandlerSyncComplete(EventWatcher watcher, BaseEventArgs evtArgs)
		{
			Log.smethod_4("MobileContactMgr", "onEventHandlerSyncComplete start prepare contact data");
			EventCenter.removeEventWatcher(EventConst.ON_SYNC_CONTACT_COMPLETE, this.mWatcherSyncComplete);
			this.mWatcherSyncComplete = null;
			List<MobileContact> hasNotUploadedContact = StorageMgr.mobileContact.getHasNotUploadedContact();
			if (hasNotUploadedContact == null)
			{
				Log.smethod_4("MobileContactMgr", "unUploadcontactList == null all contact has been uploaded!");
				return;
			}
			Log.smethod_5("MobileContactMgr", "Count need upload = " + hasNotUploadedContact.get_Count());
			if (this.mWatcherUpAndGetResult == null)
			{
				this.mWatcherUpAndGetResult = new EventWatcher(this, null, new EventHandlerDelegate(this.onEventHandlerUpAndGetResult));
				EventCenter.registerEventWatcher(EventConst.ON_NETSCENE_UPLOADCONTACT_FAIL, this.mWatcherUpAndGetResult);
				EventCenter.registerEventWatcher(EventConst.ON_NETSCENE_GETFRIEND_FAIL, this.mWatcherUpAndGetResult);
				EventCenter.registerEventWatcher(EventConst.ON_NETSCENE_GETFRIEND_SUCCESS, this.mWatcherUpAndGetResult);
			}
			Log.smethod_4("MobileContactMgr", "start upload contact!");
			this.mGetProgressBar(strings.PCon_List_MsgFetchingF);
			ServiceCenter.sceneNetUploadMContact.doScene(hasNotUploadedContact);
		}
		private void onEventHandlerUpAndGetResult(EventWatcher watcher, BaseEventArgs evtArgs)
		{
			if (this.mWatcherUpAndGetResult != null)
			{
				EventCenter.removeEventWatcher(EventConst.ON_NETSCENE_UPLOADCONTACT_FAIL, this.mWatcherUpAndGetResult);
				EventCenter.removeEventWatcher(EventConst.ON_NETSCENE_GETFRIEND_FAIL, this.mWatcherUpAndGetResult);
				EventCenter.removeEventWatcher(EventConst.ON_NETSCENE_GETFRIEND_SUCCESS, this.mWatcherUpAndGetResult);
				this.mWatcherUpAndGetResult = null;
			}
			if (evtArgs == null)
			{
				return;
			}
			switch (evtArgs.mEventID)
			{
			case EventConst.ON_NETSCENE_UPLOADCONTACT_FAIL:
			case EventConst.ON_NETSCENE_GETFRIEND_FAIL:
				Log.smethod_5("MobileContactMgr", "setLastUploadAndGetFriendResult(UP_AND_GET_RESULT_FAILED");
				this.setLastUploadAndGetFriendResult(-1);
				this.mGetProgressBar(null);
				return;
			case EventConst.ON_NETSCENE_GETFRIEND_SUCCESS:
				Log.smethod_5("MobileContactMgr", "setLastUploadAndGetFriendResult(UP_AND_GET_RESULT_SUCCESS)");
				this.setLastUploadAndGetFriendResult(1);
				this.mGetProgressBar(null);
				return;
			default:
				return;
			}
		}
		public void startReadMobileAndEmail()
		{
			EventHandler<PhoneNumEventArgs> completeEvent = new EventHandler<PhoneNumEventArgs>(this.onReadMobileAndEmailCompleted);
			Log.smethod_5("MobileContactMgr", "start getEmailAndPhoneNumList()");
			InfoQuery.getEmailAndPhoneNumList(completeEvent);
		}
		private void onReadMobileAndEmailCompleted(object sender, PhoneNumEventArgs e)
		{
			if (e == null)
			{
				Log.smethod_1("MobileContactMgr", "get device phoneNum and Email fail PhoneNumEventArgs is null");
				EventCenter.postEvent(EventConst.ON_SYNC_CONTACT_FAIL, null, null);
				this.mStatus = 0;
				return;
			}
			if (e.Result != null)
			{
				this.mPhoneList = e.Result;
			}
			if (this.mPhoneList.get_Count() <= 0)
			{
				EventCenter.removeEventWatcher(EventConst.ON_SYNC_CONTACT_COMPLETE, this.mWatcherSyncComplete);
				this.mWatcherSyncComplete = null;
				EventCenter.postEvent(EventConst.ON_SYNC_CONTACT_COMPLETE, null, null);
				EventCenter.postEvent(EventConst.ON_NETSCENE_GETFRIEND_FAIL, null, null);
				this.mStatus = 2;
				return;
			}
			Log.smethod_5("MobileContactMgr", "mPhoneList.Count = " + this.mPhoneList.get_Count());
			this.contactNum = this.getDeviceContactCount();
			if (!MobileContactMgr.isTimeToSyncAddrBook(Util.getNowMilliseconds()) && this.contactNum == this.mPhoneList.get_Count())
			{
				if (this.getLastUploadAndGetFriendResult() != -1)
				{
					EventCenter.removeEventWatcher(EventConst.ON_SYNC_CONTACT_COMPLETE, this.mWatcherSyncComplete);
					this.mWatcherSyncComplete = null;
					MobileContactMgr.sycFriendContact();
					EventCenter.postEvent(EventConst.ON_NETSCENE_GETFRIEND_SUCCESS, null, null);
					this.mStatus = 2;
					EventCenter.postEvent(EventConst.ON_NETSCENE_GETFRIEND_FAIL, null, null);
					goto IL_153;
				}
			}
			if (this.mPhoneList.get_Count() > 30)
			{
				this.mGetProgressBar(strings.PCon_List_MsgSncing);
			}
			this.sycMobileAndEmail();
			this.setDeviceContactCount(this.mPhoneList.get_Count());
			IL_153:
			Log.smethod_1("MobileContactMgr", "contactNum = " + this.contactNum);
		}
		private static void sycFriendContact()
		{
			List<MobileContact> hasUserNameContact = StorageMgr.mobileContact.getHasUserNameContact();
			if (hasUserNameContact != null && hasUserNameContact.get_Count() > 0)
			{
				Log.smethod_5("MobileContactMgr", "mContactList.Count = " + hasUserNameContact.get_Count());
				using (List<MobileContact>.Enumerator enumerator = hasUserNameContact.GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						MobileContact current = enumerator.get_Current();
						if (current != null)
						{
							Contact contact = StorageMgr.contact.method_0(current.strUsrName);
							if (contact != null && ContactMgr.isContact(contact))
							{
								current.strNickName = contact.strNickName;
								current.strProvince = contact.strProvince;
								current.strCity = contact.strCity;
								current.strSignature = contact.strSignature;
								current.nSex = contact.nSex;
								current.nPersonalCard = contact.nPersonalCard;
								current.nFlag = contact.nFlags;
								current.nStatus = 2;
							}
							else
							{
								current.nStatus = 1;
							}
						}
					}
				}
				StorageMgr.mobileContact.updateList(hasUserNameContact);
			}
		}
		public void sycMobileAndEmail()
		{
			if (this.mWatcherUpdateListResult == null)
			{
				this.mWatcherUpdateListResult = new EventWatcher(this, null, new EventHandlerDelegate(this.onEventHandlerUpdateListResult));
				EventCenter.registerEventWatcher(EventConst.UPDATELIST_EXCEPT_UPLOADTIME, this.mWatcherUpdateListResult);
			}
			Thread thread = new Thread(new ThreadStart(this.threadSycMobileAndEmail));
			thread.Start();
		}
		public void threadSycMobileAndEmail()
		{
			if (this.mEmailList == null && this.mPhoneList == null)
			{
				Log.smethod_1("MobileContactMgr", "Nothing can Synchronous!");
				EventCenter.postEvent(EventConst.ON_SYNC_CONTACT_FAIL, null, null);
				this.mStatus = 0;
				return;
			}
			if (this.mPhoneList != null && this.mPhoneList.get_Count() > 0)
			{
				List<MobileContact> param = this.convertToAddrUploads(this.mPhoneList, 0);
				Log.smethod_5("MobileContactMgr", "convertToAddrUploads complete");
				EventCenter.postEvent(EventConst.UPDATELIST_EXCEPT_UPLOADTIME, param, null);
			}
		}
		private void onEventHandlerUpdateListResult(EventWatcher watcher, BaseEventArgs evtArgs)
		{
			if (evtArgs.mEventID != EventConst.UPDATELIST_EXCEPT_UPLOADTIME || evtArgs.mObject == null)
			{
				Log.smethod_1("MobileContactMgr", "Sync PhoneNum failed");
				EventCenter.postEvent(EventConst.ON_SYNC_CONTACT_FAIL, null, null);
				this.mStatus = 0;
				return;
			}
			List<MobileContact> mbileContactList = (List<MobileContact>)evtArgs.mObject;
			if (!StorageMgr.mobileContact.updateListExceptUploadTime(mbileContactList))
			{
				Log.smethod_1("MobileContactMgr", "Sync PhoneNum failed");
				EventCenter.postEvent(EventConst.ON_SYNC_CONTACT_FAIL, null, null);
				this.mStatus = 0;
				return;
			}
			Log.smethod_5("MobileContactMgr", "Phone Data Sync Complete");
			StorageMgr.mobileContact.delMobileContact(this.mLastUpdateTime);
			ConfigMgr.setDouble("dblLastSyncAddbookTimeStamp", (double)this.mLastUpdateTime);
			EventCenter.postEvent(EventConst.ON_SYNC_CONTACT_COMPLETE, null, null);
			this.mStatus = 2;
			Log.smethod_5("MobileContactMgr", "Sync Complete");
		}
		public List<MobileContact> convertToAddrUploads(List<PhoneNumInfo> numInfoList, int type)
		{
			if (numInfoList == null)
			{
				return null;
			}
			Log.smethod_5("MobileContactMgr", "begin convertToAddrUploads()  numInfoList.Count =" + numInfoList.get_Count());
			List<MobileContact> list = new List<MobileContact>();
			this.mLastUpdateTime = (long)Util.getNowMilliseconds();
			using (List<PhoneNumInfo>.Enumerator enumerator = numInfoList.GetEnumerator())
			{
				while (enumerator.MoveNext())
				{
					PhoneNumInfo current = enumerator.get_Current();
					if (current != null)
					{
						string arg_58_0 = current.String_0;
						string text = current.Name;
						string text2;
						if (type == 0)
						{
							text2 = ToolFunction.GetInterNationalNumbers(current.Num);
						}
						else
						{
							text2 = current.Num;
						}
						if (text2 != null && !text2.Equals(""))
						{
							string strMD = MD5Core.GetHashString(Encoding.get_UTF8().GetBytes(text2)).ToLower();
							MobileContact mobileContact = new MobileContact();
							if (text == null)
							{
								text = "";
							}
							mobileContact.strRealName = text;
							mobileContact.strRealNamePYInitial = SortStringsByAlpha.ConvertStringToPinyinInitial(text);
							mobileContact.strRealNameQuanPin = GetPinYin.ConvertStrToQuanPin(text);
							mobileContact.strMD5 = strMD;
							mobileContact.hasHeadImg = current.hasHeadImg;
							mobileContact.lastUpdateTime = this.mLastUpdateTime;
							if (type == 0)
							{
								mobileContact.strMobile = text2;
							}
							if (type == 1)
							{
								mobileContact.strEmail = text2;
							}
							mobileContact.nType = type;
							list.Add(mobileContact);
						}
					}
				}
			}
			Log.smethod_5("MobileContactMgr", "convertToAddrUploads() complete");
			return list;
		}
		public static bool updatemContactToFriend(MobileContact mContact, bool isAdd)
		{
			if (mContact != null && mContact.strUsrName != null && mContact.strUsrName != "" && mContact.strMD5 != null && mContact.strMD5 != "")
			{
				if (isAdd)
				{
					mContact.nFlag |= 1u;
					mContact.nStatus = 2;
					StorageMgr.mobileContact.update(mContact);
				}
				else
				{
					mContact.nFlag &= 4294967294u;
					mContact.nStatus = 1;
					StorageMgr.mobileContact.update(mContact);
				}
				EventCenter.postEvent(EventConst.ON_SYNC_CONTACT_COMPLETE, null, null);
				return true;
			}
			return false;
		}
		public static int getIdByMd5(string string_0)
		{
			int result = 0;
			int result2;
			try
			{
				result = (int)ulong.Parse(string_0.Substring(0, 8), 512);
				return result;
			}
			catch (Exception ex)
			{
				Log.smethod_1("MobileContactMgr", ex.ToString());
				result2 = 0;
			}
			return result2;
		}
		public static bool isTimeToSyncAddrBook(double curTime)
		{
			double @double = ConfigMgr.getDouble("dblLastSyncAddbookTimeStamp", 0.0);
			Log.smethod_5("MobileContactMgr", string.Concat(new object[]
			{
				"curTime = ",
				curTime,
				"/r/n lastTime = ",
				@double
			}));
			if (Math.Abs(curTime - @double) - 10800000.0 > 0.0)
			{
				Log.smethod_5("MobileContactMgr", "It is the time to SyncAddrBook");
				return true;
			}
			Log.smethod_5("MobileContactMgr", "It is not the time to SyncAddrBook");
			return false;
		}
		private int getDeviceContactCount()
		{
			return ConfigMgr.getInt("nDeviceContactCount", 0);
		}
		private void setDeviceContactCount(int nCount)
		{
			ConfigMgr.setInt("nDeviceContactCount", nCount);
		}
		private int getLastUploadAndGetFriendResult()
		{
			return ConfigMgr.getInt("nLastUploadAndGetFriendResult", 0);
		}
		private void setLastUploadAndGetFriendResult(int lastUploadAndGetFriendResult)
		{
			ConfigMgr.setInt("nLastUploadAndGetFriendResult", lastUploadAndGetFriendResult);
		}
		public static bool addInBlackList(MobileContact contact)
		{
			bool result;
			try
			{
				Contact contact2 = StorageMgr.contact.method_0(contact.strUsrName);
				if (contact2 == null)
				{
					contact2 = MobileContactMgr.ConvertToContact(contact);
					StorageMgr.contact.vmethod_0(contact2);
				}
				ContactMgr.operationSetBlackList(contact2, true);
				contact.nFlag |= 8u;
				StorageMgr.mobileContact.update(contact);
				return true;
			}
			catch (Exception ex)
			{
				Log.smethod_1("MobileContactMgr", ex.ToString());
				result = false;
			}
			return result;
		}
		public static bool moveOutBlackList(MobileContact contact)
		{
			Contact contact2 = StorageMgr.contact.method_0(contact.strUsrName);
			if (contact2 == null)
			{
				Log.smethod_1("MobileContactMgr", "Can not move out BlackList, the contact is not exist");
				return false;
			}
			ContactMgr.operationSetBlackList(contact2, false);
			contact.nFlag &= 4294967287u;
			StorageMgr.mobileContact.update(contact);
			return true;
		}
		public static bool isFriend(Contact contact)
		{
			return (contact.nFlags & 1u) > 0u;
		}
		public static bool isInBlackList(MobileContact contact)
		{
			return (contact.nFlag & 8u) > 0u;
		}
		private static Contact ConvertToContact(MobileContact mobileContact)
		{
			Contact contact = new Contact();
			contact.nFlags = 0u;
			contact.strUsrName = mobileContact.strUsrName;
			contact.strSignature = mobileContact.strSignature;
			contact.strQuanPin = mobileContact.strNickNameQuanPin;
			contact.strPYInitial = mobileContact.strNickNamePYInitial;
			contact.strMobile = mobileContact.strMobile;
			contact.strNickName = mobileContact.strNickName;
			contact.strEmail = mobileContact.strEmail;
			contact.strCity = mobileContact.strCity;
			contact.strProvince = mobileContact.strProvince;
			contact.nPersonalCard = mobileContact.nPersonalCard;
			contact.nFlags |= 2u;
			return contact;
		}
		public MobileContact getMobileContactByUserName(string strUserName)
		{
			return StorageMgr.mobileContact.getByUserName(strUserName);
		}
		public MobileContact getMobileContactByPhoneNumberMD5(string string_0)
		{
			return StorageMgr.mobileContact.method_7(string_0);
		}
		public static void init()
		{
			EventCenter.registerEventHandler(EventConst.ON_STORAGE_CHAT_MSG_ADD, new EventHandlerDelegate(MobileContactMgr.onChatMsgAdd));
		}
		private static void onChatMsgAdd(EventWatcher watcher, BaseEventArgs evtArgs)
		{
			List<ChatMsg> listObject = evtArgs.getListObject<ChatMsg>();
			if (listObject == null)
			{
				return;
			}
			using (List<ChatMsg>.Enumerator enumerator = listObject.GetEnumerator())
			{
				while (enumerator.MoveNext())
				{
					ChatMsg current = enumerator.get_Current();
					MobileContactMgr.saveContactInfoIfNeed(current);
				}
			}
		}
		private static void saveContactInfoIfNeed(ChatMsg chatMsg_0)
		{
			if (chatMsg_0 == null)
			{
				return;
			}
			int scene = FMsgMgr.getScene(chatMsg_0);
			if (scene == 10)
			{
				try
				{
					XDocument xDocument = XDocument.Parse(chatMsg_0.strMsg);
					XElement xElement = xDocument.Element("msg");
					string userName = null;
					string phoneMD = null;
					XAttribute xAttribute = xElement.Attribute("fromusername");
					if (xAttribute != null)
					{
						userName = xAttribute.get_Value();
					}
					xAttribute = xElement.Attribute("mobileidentify");
					if (xAttribute != null)
					{
						phoneMD = xAttribute.get_Value();
					}
					ServiceCenter.mobileContactMgr.updateUserNameByPhoneMD5(phoneMD, userName);
				}
				catch (Exception ex)
				{
					Log.smethod_1("error->MobileContactMgr->saveContactInfoIfNeed xmlStr:" + chatMsg_0.strMsg, ex.get_Message());
				}
			}
		}
		public void updateUserNameByPhoneMD5(string phoneMD5, string userName)
		{
			if (phoneMD5 == null || userName == null)
			{
				return;
			}
			MobileContact mobileContact = StorageMgr.mobileContact.method_7(phoneMD5);
			if (mobileContact != null && mobileContact.strUsrName == null)
			{
				mobileContact.strUsrName = userName;
				StorageMgr.mobileContact.update(mobileContact);
				return;
			}
			if (mobileContact != null && userName != mobileContact.strUsrName)
			{
				mobileContact.strUsrName = userName;
				StorageMgr.mobileContact.update(mobileContact);
			}
		}
	}
}
